package com.vcredit.creditcat.time;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.threadpool.RequestLocalThread;
import com.vcredit.creditcat.manager.TimeManager;
import com.vcredit.creditcat.model.AuthAccumulation;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;

/**
 * 公积金认证后台任务表
 * @author xiaojingjing
 *
 */
@JobHander(value="accumulationTime")
@Component
public class AccumulationTime extends IJobHandler {

	private static Logger logger = LoggerFactory.getLogger(AccumulationTime.class);

	@Autowired
	private TimeManager<AuthAccumulation> accTimeManager;

	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	@Override
	public ReturnT<String> execute(String... strings) throws Exception {
		logger.info("公积金认证定时任务执行了................" + ConcurrentDateUtil.formatDateTime(new Date()));
		RequestLocalThread.create();
		List<AuthAccumulation> list = null;
		try {
			list = accTimeManager.findUnCrawl(AuthAccumulation.class);
			if (list == null || list.isEmpty())
				return ReturnT.SUCCESS;
			for (AuthAccumulation obj : list) {
				threadPoolTaskExecutor.execute(new AccumulationCrawleThread(obj));
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ReturnT.FAIL;
		}
		return ReturnT.SUCCESS;
	}

	class AccumulationCrawleThread implements Runnable {
		private AuthAccumulation obj;

		public AccumulationCrawleThread(AuthAccumulation obj) {
			this.obj = obj;
		}

		public void run() {
			try {
				accTimeManager.updateCrawlerState(obj);
			} catch (Exception e) {
				logger.error("Exception occured", e);
			}

		}
	}

}
